<template>
  <div class="index">
    <input type="text" v-model="searchText"/>
    <button class="search">搜索</button>
    <button class="add" @click="addinfo">添加</button>
    <v-table @udInfo="udInfo" :myinfo="searchInfo" @del="info.splice($event,1)"></v-table>
    <v-form v-show="isshow"
            @cal="isshow=false" 
            :isAdd="isAdd" 
            @add="add" 
            ref="form" 
            @ud="ud"></v-form>
  </div>
</template>

<script>
import vTable from "./table.vue";
import vForm from "./form.vue";
export default {
  components: {
    vTable,
    vForm
  },
  data() {
    return {
      info: [
        { id: 1, title: "娱乐新闻", con: "娱乐新闻内容" },
        { id: 2, title: "军事新闻", con: "军事新闻内容" },
        { id: 3, title: "财经新闻", con: "财经新闻内容" }
      ],
      isshow:false,
      isAdd:true,
      searchText:""
    };
  },
  computed:{
    searchInfo(){
      return this.info.filter(
        (item)=>item.title.includes(this.searchText)||item.con.includes(this.searchText)
      );
    }
  },
  methods:{
    // 点击添加按钮
    addinfo(){
      this.isshow=true;
      this.isAdd=true;
    },
    // 点击修改按钮
    udInfo(index){
      this.isshow = true;
      this.isAdd=false;

      this.$refs.form.user = {...this.info[index]};
    },
    // 添加数据
    add(user){
      this.info=[
        ...this.info,
        {
          id:new Date().getTime(),
          ...user
        }
      ];
      this.$refs.form.empty();
      this.isshow=false;
    },
    // 修改数据
    ud(user){
      let index = this.info.findIndex((item)=>item.id===user.id);
      this.info.splice(index,1,user);
      this.$refs.form.empty();
      this.isshow=false;
    }
  }
};
</script>

<style>
.add {
  float: right;
}
</style>